package com.mz.service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

public class CommonService {

	/**
	 * 将实体类转换成SQL查询语句
	 * @param object
	 * @param tableAlias
	 * @return
	 */
	public static String objectToWhere(Object object){
		return objectToWhere(object, null);
	}
	
	/**
	 * 将实体类转换成SQL查询语句
	 * @param object
	 * @param tableAlias
	 * @return
	 */
	public static String objectToWhere(Object object, String tableAlias){
		StringBuffer where = new StringBuffer(); 
		Class<?> clas = object.getClass();
		
		Field[] fields = clas.getDeclaredFields();
		String name = null, nameG = null, typeName = null;
		Method method = null;
		
		if(tableAlias==null){
			tableAlias = "";
		}else{
			tableAlias += ".";
		}
		
		try {
			for(Field field : fields){
				name = field.getName();
				nameG = name.substring(0, 1).toUpperCase() + name.substring(1);
				typeName = field.getGenericType().getTypeName();
				typeName = typeName.substring(typeName.lastIndexOf(".")+1);
				
				method = clas.getMethod("get" + nameG);
				Object value = method.invoke(object);
				if(value==null || "".equals(value.toString())){
					continue;
				}
					
				where.append(tableAlias+name);
				switch(typeName){
					case "Integer":
						where.append("=" + (Integer) value + " and ");
						break;
					case "Long":
						where.append("=" + (Long) value + " and ");
						break;
					case "Date":
						Date date = (Date) value;
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						where.append("='"+format.format(date) + "' and ");
						break;
					default:
						String val = value.toString();
						if(val.indexOf("like")>=0 || val.indexOf("LIKE")>=0){
							where.append(val + " and ");
						}else{
							where.append("='" + val + "' and ");
						}
						break;
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String result = where.toString();
		if(!StringUtils.isEmpty(result)){
			result = " " + result.substring(0, result.length()-5);
		}
		return result;
	}
	
	public static void main(String[] args) throws Exception {
		/*SysRole sysRole = new SysRole();
		sysRole.setRoleId(1L);
		sysRole.setRoleName("管理员");
		System.out.println(CommonService.objectToWhere(sysRole));*/
		System.err.println(new Date());
		
	}
	
}